package com.gaoxin.api.util;

import java.util.Date;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSONObject;
import com.gaoxin.api.entity.ConfigEntity;

@Component
public class HttpClientUtil {
	@Autowired
	private RestTemplate restTemplate;
	@Autowired
	private ConfigEntity configEntity;

	private RandomStrUtils randomStr = RandomStrUtils.getInstance();

	public String sendPostReq(String url, JSONObject reqDataObject) {
		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

		String appKey = configEntity.getAppkey();
		headers.set("AppKey", appKey);

		String nonce = randomStr.getRandomString();
		headers.set("Nonce", nonce);

		String curTime = String.valueOf((new Date()).getTime() / 1000L);
		headers.set("CurTime", curTime);

		String appSecret = configEntity.getAppSecret();

		String checkSum = CheckSumBuilder.getCheckSum(appSecret, nonce, curTime);

		headers.set("CheckSum", checkSum);

		MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
		Map data = reqDataObject;
		params.setAll(data);
		HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<MultiValueMap<String, String>>(params,
				headers);
		ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);
		return response.getBody();
	}

}
